package client.view;


import javafx.application.Application;
import javafx.application.Platform;
import javafx.event.ActionEvent;
import javafx.geometry.Insets;
import javafx.geometry.Pos;
import javafx.geometry.Side;
import javafx.scene.Scene;
import javafx.scene.control.Button;
import javafx.scene.control.ContextMenu;
import javafx.scene.control.Label;
import javafx.scene.control.MenuButton;
import javafx.scene.control.ScrollPane;
import javafx.scene.control.TextArea;
import javafx.scene.image.Image;
import javafx.scene.image.ImageView;
import javafx.scene.layout.BorderPane;
import javafx.scene.layout.HBox;
import javafx.scene.layout.Pane;
import javafx.scene.layout.Region;
import javafx.scene.layout.StackPane;
import javafx.scene.layout.VBox;
import javafx.scene.paint.Color;
import javafx.scene.text.Font;
import javafx.scene.text.FontWeight;
import javafx.scene.text.Text;
import javafx.scene.text.TextAlignment;
import javafx.scene.text.TextFlow;
import javafx.stage.FileChooser;
import javafx.stage.Stage;
import javafx.stage.StageStyle;
import jdk.internal.org.objectweb.asm.tree.IntInsnNode;
import javafx.scene.control.MenuItem;
import model.Crypto;
import model.Message;
import model.MsgType;

import java.awt.*;
import java.io.BufferedInputStream;
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.OutputStream;
import java.net.Socket;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.AbstractMap;
import java.util.Vector;
import java.util.concurrent.BlockingQueue;
import java.util.concurrent.LinkedBlockingQueue;

import javax.swing.table.TableStringConverter;

import com.google.gson.Gson;
import com.sun.org.apache.bcel.internal.generic.NEW;

import client.MessageSender;
import client.main.Client_main;
import client.service.HandleMessage;

// 聊天界面，点击“消息记录”按钮即可显示聊天记录，再次点击即可切换回图片

public class Chat extends Application {

	private BlockingQueue<Pair<Integer, String>> messageQueue = new LinkedBlockingQueue<>();
	
	private BorderPane cardLayout;//卡片布局
	private Pane panel_north;//北部区域面板
	// private Label jbl_touxiang;//头像
	private Label jbl_friendname;//好友名称
	private Button btn_exit, btn_min;//最小化和关闭按钮

	private Pane panel_south;//南部区域面板
	private TextArea jtp_input;//消息输入区
	private Button btn_pic;//图片按钮
	private Button btn_file;//文件按钮
	private Button btn_gfile;//获得文件按钮
	private Button btn_send, btn_close;//消息输入区下方关闭和发送按钮

    //默认东部面板显示一张图,点击查询聊天记录按钮切换到聊天记录面板
	//private Label label1;
	//private TextArea panel_Record;//聊天记录显示面板
	private String myName;
	private String roomName;//房间名字
	private int userId = 2;
	private int roomId = 3;
	private Vector<Integer> friendIds;
	private Vector<String> friendNames;
     
	private Text text;
	private HBox msgBox;
	private VBox msg;
	private VBox chatBox;
     
     // 通信逻辑
	private Socket client;
	private DataInputStream dis;
	private DataOutputStream dos;
	private MessageReceiver messageReceiver;
	// private MessageSender messageSender;
	
    private double xOffset = 0;
    private double yOffset = 0;
     
	private String prefix = "file:image/dialogimage/";
    
   public Chat(int userId, String myName,int roomId ,Vector<Integer> friendIds, Vector<String> friendNames,String roomName) {

       this.userId = userId;
       this.roomId = roomId;
       this.myName = myName;
       this.roomName = roomName;
       this.friendIds = friendIds;
       this.friendNames = friendNames;
     // 还要连接socket
		String host = Client_main.ip;
		int port = 12345;
		try {
			client = new Socket(host, port);
			dis = new DataInputStream(client.getInputStream());
			dos = new DataOutputStream(client.getOutputStream());
			messageReceiver = new MessageReceiver(dis);
		} catch (Exception e) {
			// TODO: handle exception
		}
   }
	
     private class PhotoMenuItem extends MenuItem {
    	    private Image photo;

    	    public PhotoMenuItem(String url) {
    	        this.photo = new Image(url);
    	        ImageView imageView = new ImageView(photo);
    	        imageView.setFitWidth(50);
    	        imageView.setFitHeight(50);
    	        setGraphic(imageView);

    	        // 点击事件处理
    	        setOnAction(e -> {
    	            // 在此处理照片的发送逻辑
    	            System.out.println("发送照片: " + url);
    	            showMyPic(url, getTime());
    	    		Gson gson = new Gson();
    	    		Message mes = new Message();
    	    		mes.setText(url);
    	    		mes.setRoomID(roomId);
    	    		mes.setType(MsgType.COMMON_MESSAGE);
    	    		mes.setUserID(userId);
    	    		
    	    		String json = gson.toJson(mes);
    	    		try {
    	        	String encryptedMessage = Crypto.encrypt(json);
    	        	dos.writeUTF(encryptedMessage);
    	    		System.out.println("发送消息");
    	    		dos.flush();
    	    		} catch (Exception ee) {
    	    			// TODO: handle exception
    	    			ee.getMessage();
    	    		}
    	        });
    	    }
    	}
     
     
    @Override
    public void start(Stage primaryStage) {
    	    	
        primaryStage.getIcons().add(new Image("file:image/login/Q.png"));
        primaryStage.setTitle("ChatBox");


        cardLayout = new BorderPane();
        cardLayout.setPrefSize(800, 600);
        cardLayout.setVisible(true);//设置窗体可见

        Scene scene = new Scene(cardLayout);

        //北部面板
        panel_north = new Pane();
        panel_north.setPrefWidth(800);
        panel_north.setPrefHeight(70);
        cardLayout.setTop(panel_north);


        //左上角灰色头像
        String turl;
        if(friendIds.size() == 2)
        	turl = "file:image/dialogimage/touxiangl.png";
        else
        	turl = "file:image/dialogimage/qunliao.png";
        ImageView jbl_touxiang = new ImageView(new Image(turl));
        jbl_touxiang.setLayoutX(5);
        jbl_touxiang.setLayoutY(5);
        jbl_touxiang.setFitWidth(60);
        jbl_touxiang.setFitHeight(60);
        panel_north.getChildren().add(jbl_touxiang);

        //头像右方正在聊天的对方姓名
        jbl_friendname = new Label(roomName);
        jbl_friendname.setTextAlignment(TextAlignment.CENTER);
        jbl_friendname.setLayoutX(320);
        jbl_friendname.setLayoutY(20);
        jbl_friendname.setPrefWidth(300);
        jbl_friendname.setPrefHeight(20);
        jbl_friendname.setFont(Font.font("Arial", FontWeight.BOLD, 24));
        panel_north.getChildren().add(jbl_friendname);

        //右上角最小化按钮
        btn_min=new Button();
        ImageView imageView1 = new ImageView(new Image("file:image/dialogimage/min.png"));
        btn_min.setGraphic(imageView1);
        btn_min.setOnAction(e -> primaryStage.setIconified(true));
        btn_min.setLayoutX(740);
        btn_min.setLayoutY(0);
        btn_min.setMaxWidth(50);
        btn_min.setMaxHeight(50);
        btn_min.setPadding(new Insets(0));
        panel_north.getChildren().add(btn_min);

        //右上角关闭按钮
        btn_exit = new Button();
        ImageView imageView2 = new ImageView(new Image("file:image/dialogimage/exit.jpg"));
        btn_exit.setGraphic(imageView2);
        btn_exit.setLayoutX(770);
        btn_exit.setLayoutY(0);
        btn_exit.setMaxWidth(50);
        btn_exit.setMaxHeight(50);
        btn_exit.setOnAction(e -> {
    		Gson gson = new Gson();
    		Message mes = new Message();
    		mes.setType(MsgType.CLOSE_MESSAGE);
    		String json = gson.toJson(mes);
    		try {
    		String encryptedMessage = Crypto.encrypt(json);
    		dos.writeUTF(encryptedMessage);
    		System.out.println("发送消息,再见");
    		dos.flush();
    		} catch (Exception ee) {
    			// TODO: handle exception
    			ee.getMessage();
    		}
        	primaryStage.close();
        });
        btn_exit.setPadding(new Insets(0));
        panel_north.getChildren().add(btn_exit);

        //设置北部面板背景色
        panel_north.setStyle("-fx-background-color: #169AE4;"); // 设置背景颜色
     
        //中部聊天内容显示部分
        chatBox = new VBox(); // 创建垂直布局容器
        chatBox.setSpacing(20);
        HBox spaceBox = new HBox();
        chatBox.getChildren().add(spaceBox);
        
        // 将消息添加到垂直布局容器中
        ScrollPane scrollPane_Msg = new ScrollPane(chatBox); // 创建包含消息的滚动窗格
        scrollPane_Msg.setLayoutX(0);
        scrollPane_Msg.setLayoutY(0);
        scrollPane_Msg.setMinSize(800,500);
        scrollPane_Msg.vvalueProperty().bind(chatBox.heightProperty()); // 将vvalue属性绑定到chatBox的高度
        cardLayout.setCenter(scrollPane_Msg);
                
        
        //南部面板
        panel_south = new Pane();
        panel_south.setLayoutX(0);
        panel_south.setLayoutY(0);
        panel_south.setPrefWidth(800);
        panel_south.setPrefHeight(190);
        cardLayout.setBottom(panel_south);

        //内容输入区
        jtp_input = new TextArea();
        jtp_input.setWrapText(true); // 启用自动换行
        jtp_input.setStyle("-fx-font-size: 18px; -fx-text-fill: #000000;");
        jtp_input.setLayoutX(0);
        jtp_input.setLayoutY(30);
        jtp_input.setMaxWidth(800);
        jtp_input.setMinWidth(800);
        jtp_input.setPrefHeight(130);
        //添加到南部面板
        panel_south.getChildren().add(jtp_input);

        //图片按钮
        btn_pic = new Button();
        ImageView imageView3 = new ImageView(new Image("file:image/dialogimage/biaoqing.png"));
        btn_pic.setGraphic(imageView3);
        btn_pic.setMaxSize(20, 20);
        btn_pic.setMinSize(20, 20);
        btn_pic.setOnAction(e -> {
            // 创建菜单项
            PhotoMenuItem emojiItem1 = new PhotoMenuItem("file:image/dialogimage/1.jfif");
            PhotoMenuItem emojiItem2 = new PhotoMenuItem("file:image/dialogimage/2.jfif");
            PhotoMenuItem emojiItem3 = new PhotoMenuItem("file:image/dialogimage/3.jfif");
            PhotoMenuItem emojiItem4 = new PhotoMenuItem("file:image/dialogimage/4.jfif");
            PhotoMenuItem emojiItem5 = new PhotoMenuItem("file:image/dialogimage/5.jfif");

            // 创建ContextMenu
            ContextMenu contextMenu = new ContextMenu(emojiItem1, emojiItem2, emojiItem3, emojiItem4, emojiItem5);

            // 关联ContextMenu与按钮
            contextMenu.show(btn_pic, Side.TOP, 0, 0);
        });

        btn_pic.setLayoutX(5);
        btn_pic.setLayoutY(5);
        panel_south.getChildren().add(btn_pic);
        
        //文件按钮
        btn_file = new Button();
        ImageView imageView6 = new ImageView(new Image("file:image/dialogimage/tranfile.jpg"));
        btn_file.setGraphic(imageView6);
        btn_file.setMaxSize(20, 20);
        btn_file.setMinSize(20, 20);
        btn_file.setOnAction(e -> {
            FileChooser fileChooser = new FileChooser();

            // 设置文件对话框的标题和初始目录
            fileChooser.setTitle("选择文件");
            fileChooser.setInitialDirectory(new File(System.getProperty("user.home")));

            // 打开文件对话框并获取用户选择的文件
            File selectedFile = fileChooser.showOpenDialog(primaryStage);
            if (selectedFile != null) {
                // 选择了文件，在这里进行处理
                System.out.println("选择的文件路径：" + selectedFile.getAbsolutePath());
                // 打开或查看文件
                showMyPic("file:image/dialogimage/wenjian.jfif", getTime());
	            // 在后台线程执行传输文件操作
	            new Thread(() -> {
	                sendFile(selectedFile);
	            }).start();
            } else {
                // 用户取消了选择
                System.out.println("未选择任何文件");
            }
        });
        btn_file.setLayoutX(40);
        btn_file.setLayoutY(5);
        panel_south.getChildren().add(btn_file);
        
        // 查看文件按钮
        btn_gfile = new Button();
        ImageView imageView7 = new ImageView(new Image("file:image/dialogimage/dgninput.jpg"));
        btn_gfile.setGraphic(imageView7);
        btn_gfile.setMaxSize(20, 20);
        btn_gfile.setMinSize(20, 20);
        btn_gfile.setOnAction(e -> {
        	
            // 创建文件夹
            String folderPath = "." + File.separator + "file" + File.separator + userId;
            File folder = new File(folderPath);
            if (!folder.exists()) {
                folder.mkdir();
                System.out.println("文件夹 " + userId + " 创建成功");
            } else {
                System.out.println("文件夹 " + userId + " 已存在，无需创建");
            }
        	
            // 创建一个文件选择器
            FileChooser fileChooser = new FileChooser();

            // 设置选择器的标题和初始目录
            fileChooser.setTitle("选择要打开的文件");
            File initialDirectory = new File(folderPath);
            fileChooser.setInitialDirectory(initialDirectory);
            // 显示文件选择器并获取选定的文件
            File selectedFile = fileChooser.showOpenDialog(primaryStage);

            // 如果有文件被选定
            if (selectedFile != null) {
                // 使用系统默认的文件打开器打开文件
                try {
                    Desktop.getDesktop().open(selectedFile);
                } catch (Exception ee) {
                    ee.printStackTrace();
                }
            }
        });
        btn_gfile.setLayoutX(75);
        btn_gfile.setLayoutY(5);
        panel_south.getChildren().add(btn_gfile);
        
        //消息关闭按钮
        btn_close = new Button();
        ImageView imageView4 = new ImageView(new Image("file:image/dialogimage/close.jpg"));
        btn_close.setGraphic(imageView4);
        btn_close.setLayoutX(640);
        btn_close.setLayoutY(160);
        btn_close.setPrefWidth(55);
        btn_close.setPrefHeight(25);
        btn_close.setOnAction(e->clear(e));
        panel_south.getChildren().add(btn_close);

        //消息发送按钮
        btn_send = new Button();
        ImageView imageView5 = new ImageView(new Image("file:image/dialogimage/send.jpg"));
        btn_send.setGraphic(imageView5);
        btn_send.setLayoutX(720);
        btn_send.setLayoutY(160);
        btn_send.setPrefWidth(55);
        btn_send.setPrefHeight(25);
        btn_send.setOnAction(e->send(e));
        panel_south.getChildren().add(btn_send);

        primaryStage.setScene(scene);
        primaryStage.show();
        
        // 以下进行逻辑处理
        initHistory();
        // 定期检查消息队列并更新界面,辅助线程，更新javafx线程
        Thread updateThread = new Thread(() -> {
            while (true) {
                try {
                    Pair<Integer, String> pair = messageQueue.take();
        			System.out.println(pair);
        			String text = pair.getValue();
        			System.out.println(text);
        			Integer fId = pair.getKey();
        			System.out.println(fId);
        			String fName = friendNames.elementAt(friendIds.indexOf(fId));
        			
        			
                    Platform.runLater(() -> {
                        // 在 JavaFX Application 线程中更新界面
        				if(text.startsWith(prefix)) // 照片
        					showFriendPic(fName, text, getTime());
        				else // 文本
        					showFriendMsg(fName, text, getTime());
                    });
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        });
        updateThread.start();
    }

    public void showFriendMsg(String fName, String msgString, String time) {
        msgBox = new HBox();
        msg = new VBox();
        msg.setMaxWidth(530);
        msg.setMinWidth(530);
        Region space1 = new Region();
        space1.setMaxWidth(20);
        space1.setMinWidth(20);
        // 创建好友发送消息的 HBox，并设置样式和对齐方式
        Text info = new Text(fName + "   " + time);
        info.setStyle("-fx-background-color: #8BC34A; -fx-padding: 10px; -fx-text-fill: #8F1000; -fx-font-size: 20px;");
        info.setTextAlignment(TextAlignment.LEFT);
        info.setFill(Color.DARKVIOLET);
        text = new Text(msgString);
        text.setWrappingWidth(520);
        text.setStyle("-fx-background-color: #8BC34A; -fx-padding: 10px; -fx-text-fill: #FFFFFF; -fx-font-size: 25px;");
        msg.getChildren().addAll(info, text);
        msgBox.getChildren().addAll(space1, msg);
        chatBox.getChildren().add(msgBox);
    }
    
    public void showMyMsg(String msgString, String time) {
    	HBox msgBox = new HBox();
        VBox msg = new VBox();
        Region space2 = new Region();
        space2.setMaxWidth(250);
        space2.setMinWidth(250);
        // 创建我发送消息的 HBox，并设置样式和对齐方式
        Text info  = new Text(myName + "   " + time);
        info.setWrappingWidth(520);
        info.setStyle("-fx-background-color: #8BC34A; -fx-padding: 10px; -fx-text-fill: #8F1000; -fx-font-size: 20px;");
        info.setTextAlignment(TextAlignment.RIGHT);
        info.setFill(Color.DARKGOLDENROD);
        text= new Text(msgString);
        text.setWrappingWidth(520);
        text.setStyle("-fx-background-color: #8BC34A; -fx-padding: 10px; -fx-text-fill: #FFFFFF; -fx-font-size: 25px;");
        text.setTextAlignment(TextAlignment.RIGHT);
        msg.setMaxWidth(530);
        msg.setMinWidth(530);
        msg.getChildren().addAll(info, text);
        msgBox.getChildren().addAll(space2, msg);
        chatBox.getChildren().add(msgBox); 
    }
    
    public void showMyPic(String url, String time) {
    	System.out.println(url);
    	// 信息发送
    	HBox msgBox1 = new HBox();
        VBox msg1 = new VBox();
        Region space3 = new Region();
        space3.setMaxWidth(250);
        space3.setMinWidth(250);
        // 创建我发送消息的 HBox，并设置样式和对齐方式
        text= new Text(myName + "   " + time);
        text.setWrappingWidth(520);
        text.setStyle("-fx-background-color: #8BC34A; -fx-padding: 10px; -fx-text-fill: #FFFFFF; -fx-font-size: 20px;");
        text.setTextAlignment(TextAlignment.RIGHT);
        text.setFill(Color.DARKGOLDENROD);
        msg1.setMaxWidth(530);
        msg1.setMinWidth(530);
        msg1.getChildren().add(text);
        msgBox1.getChildren().addAll(space3, msg1);
        chatBox.getChildren().add(msgBox1); 
    	
    	// 照片发送
    	HBox msgBox = new HBox();
        VBox msg = new VBox();
        Region space2 = new Region();
        space2.setMaxWidth(550);
        space2.setMinWidth(550);
        // 照片
        ImageView imageView = new ImageView(new Image(url));
        imageView.setFitWidth(200);
        imageView.setPreserveRatio(true);
        imageView.setStyle("-fx-background-color: #8BC34A; -fx-padding: 10px;");
        imageView.setSmooth(true);
        imageView.setCache(true);
        msg.setMaxWidth(200);
        msg.setMinWidth(200);
        msg.getChildren().add(imageView);
        msgBox.getChildren().addAll(space2, msg);
        chatBox.getChildren().add(msgBox); 
    }
    
    public void showFriendPic(String fName, String url, String time) {
    	// 信息
        msgBox = new HBox();
        msg = new VBox();
        msg.setMaxWidth(530);
        msg.setMinWidth(530);
        Region space1 = new Region();
        space1.setMaxWidth(20);
        space1.setMinWidth(20);
        // 创建本人发送消息的 HBox，并设置样式和对齐方式
        text = new Text(fName + "   " + time);
        text.setWrappingWidth(520);
        text.setStyle("-fx-background-color: #8BC34A; -fx-padding: 10px; -fx-text-fill: #FFFFFF; -fx-font-size: 20px;");
        text.setFill(Color.DARKVIOLET);
        msg.getChildren().add(text);
        msgBox.getChildren().addAll(space1, msg);
        chatBox.getChildren().add(msgBox);
        
    	// 照片发送
    	HBox msgBox1 = new HBox();
        VBox msg1 = new VBox();
        msg1.setMaxWidth(530);
        msg1.setMinWidth(530);
        Region space3 = new Region();
        space3.setMaxWidth(20);
        space3.setMinWidth(20);
        // 照片
        ImageView imageView = new ImageView(new Image(url));
        imageView.setFitWidth(200);
        imageView.setPreserveRatio(true);
        imageView.setStyle("-fx-background-color: #8BC34A; -fx-padding: 10px;");
        imageView.setSmooth(true);
        imageView.setCache(true);
        msg.setMaxWidth(200);
        msg.setMinWidth(200);
        msg.getChildren().add(imageView);
        msgBox1.getChildren().addAll(space3, msg1);
        chatBox.getChildren().add(msgBox1);
    }
    
    public void send(ActionEvent e) {
    	showMyMsg(jtp_input.getText(), getTime());
		Gson gson = new Gson();
		Message mes = new Message();
		mes.setText(jtp_input.getText());
		mes.setRoomID(roomId);
		mes.setType(MsgType.COMMON_MESSAGE);
		mes.setUserID(userId);
		
		String json = gson.toJson(mes);
		try {
		String encryptedMessage = Crypto.encrypt(json);
		dos.writeUTF(encryptedMessage);
		System.out.println("发送消息");
		dos.flush();
		} catch (Exception ee) {
			// TODO: handle exception
			ee.getMessage();
		}
		jtp_input.clear();
    }
    
    public void sendFile(File file) {
    	byte[] fileBytes = new byte[(int) file.length()];
        // 读取文件内容到字节数组
    	try {
    		FileInputStream fileInputStream = new FileInputStream(file);
    		BufferedInputStream bufferedInputStream = new BufferedInputStream(fileInputStream);
    		bufferedInputStream.read(fileBytes, 0, fileBytes.length);
    		
    		Gson gson = new Gson();
    		Message mes = new Message();
    		mes.setText("file:image/dialogimage/wenjian.jfif");
    		mes.setRoomID(roomId);
    		mes.setType(MsgType.FILE_MESSAGE);
    		mes.setUserID(userId);
    		String json = gson.toJson(mes);
    		String encryptedMessage = Crypto.encrypt(json);
    		dos.writeUTF(encryptedMessage);
    		System.out.println("发送文件先决消息");
    		dos.flush();
    		dos.writeUTF(file.getName());
            dos.writeLong(file.length());
            dos.write(fileBytes, 0, fileBytes.length);
            dos.flush();
            System.out.println("发送文件消息"); 
            bufferedInputStream.close();
    	} catch (Exception e) {
			// TODO: handle exception
		}
    }
    
    public void clear(ActionEvent e) {
    	jtp_input.clear();
    }

    public String getTime() {
        LocalDateTime now = LocalDateTime.now();
        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
        return now.format(formatter);
    }
    
    public void initHistory() {
    	/*
		String host = "127.0.0.1";
		int port = 12345;
		try {
			client = new Socket(host, port);
			dis = new DataInputStream(client.getInputStream());
			dos = new DataOutputStream(client.getOutputStream());
		} catch (Exception e) {
			// TODO: handle exception
		}
    	*/
			Vector<model.Message> history = new HandleMessage(dis, dos).initHistory(userId, roomId); 
			for(int i = 0; i < history.size(); i++) {
				int talkerId = history.elementAt(i).getUserID();
				String text = history.elementAt(i).getText();
				String time = history.elementAt(i).getTime();
				System.out.println(friendNames);
				System.out.println(friendIds);
				String fName = friendNames.elementAt(friendIds.indexOf(talkerId));
				
				if(talkerId == userId) { // 我的消息
					if(text.startsWith(prefix)) // 照片
						showMyPic(text, time);
					else // 文本
						showMyMsg(text, time);
				} else { // 别人的
					if(text.startsWith(prefix)) // 照片
						showFriendPic(fName, text, time);
					else // 文本
						showFriendMsg(fName, text, time);
				}
			}
			// 同时初始化接收线程
            Thread t = new Thread(messageReceiver);
            t.start();
    }
    
    // 消息接收内部类
    //此类用来获取服务端发送给客户端的数据
    class MessageReceiver implements Runnable{
    	private DataInputStream mdis;
    	public boolean flag=true;
    	public boolean isFile = false;
    	
    	//构造函数
    	public MessageReceiver(DataInputStream dis)
    	{
    		System.out.println("MessageReceiver构造");
    		this.mdis = dis;
    	}
    	
    	private Pair<Integer, String> Receive()
    	{
    		try
    		{
    			Gson gson = new Gson();
    			System.out.println("MessageReceiver尝试接收");
    			String encryptedMessage = mdis.readUTF();
    			String json = Crypto.decrypt(encryptedMessage);
    			Message mes = gson.fromJson(json, Message.class);
    			if(mes.getType() == MsgType.COMMON_MESSAGE) {
    				return new Pair<Integer, String>(mes.getUserID(), mes.getText());
    			} else if(mes.getType() == MsgType.FILE_MESSAGE) {
    				isFile = true;
    				return new Pair<Integer, String>(mes.getUserID(), mes.getText());
    			} else if(mes.getType() == MsgType.CONFIRM_CLOSE) {
    				flag = false;
    				client.close();
    			}
    			return null;
    		}catch (Exception e)
    		{
    			flag = false;
    			e.printStackTrace();
    			return null;
    		}
    	}
    	
    	public void run()
    	{
    		System.out.println("MessageReceiver开跑");
    		while(flag)
    		{
    			Pair<Integer, String> pair = this.Receive();
    			if(flag) {
    			messageQueue.offer(pair);
                try {
                    Thread.sleep(500);
                } catch (InterruptedException e) {
                    e.printStackTrace();
    			// System.out.println(pair);
                }
                if(isFile) {
                	isFile = false;
                	try {
                	// 接收文件
                    String fileName = mdis.readUTF();
                    long fileSize = mdis.readLong();
                    byte[] fileBytes = new byte[(int) fileSize];
                    mdis.readFully(fileBytes, 0, fileBytes.length);
                    System.out.println(userId + "成功接收长度" + fileSize + "的文件" + fileName);
                    // 存到本地
                    // 创建文件夹
                    String folderPath = "." + File.separator + "file" + File.separator + userId;
                    File folder = new File(folderPath);
                    if (!folder.exists()) {
                        folder.mkdir();
                        System.out.println("文件夹 " + userId + " 创建成功");
                    } else {
                        System.out.println("文件夹 " + userId + " 已存在，无需创建");
                    }
                    // 保存文件
                    String filePath = folderPath + File.separator + fileName;
                    OutputStream os = new FileOutputStream(filePath);
                    os.write(fileBytes);
                    System.out.println("文件保存成功：" + filePath);
                    os.close();
                	} catch (Exception e) {
						// TODO: handle exception
					}
                }
    			}
    		}
    	}
    }
    
	public class Pair<K, V> extends AbstractMap.SimpleEntry<K, V> {
        public Pair(K key, V value) {
            super(key, value);
        }
    }	
}